<template>
    <el-table :data="articleList" style="width: 100%; height: 85vh" class="custom-table">
        <!-- 封面 -->
        <el-table-column label="封面" header-align="center">
            <template #default="scope">
                <el-image style="width: 100px; height: 60px; border-radius: 4px" :src="scope.row.cover_image"
                    fit="cover" />
            </template>
        </el-table-column>

        <!-- 文章标题 -->
        <el-table-column prop="title" label="标题" header-align="center" />

        <!-- 文章分类 -->
        <el-table-column prop="category" label="分类" header-align="center" />

        <!-- 文章标签 -->
        <el-table-column prop="tags" label="标签" header-align="center">
            <template #default="scope">
                <el-tag v-for="tag in scope.row.tags" :key="tag" style="margin:0 5px 5px 0">
                    {{ tag }}
                </el-tag>
            </template>
        </el-table-column>

        <!-- 发布时间 -->
        <el-table-column prop="publish_time" label="发布时间" header-align="center">
            <template #default="{ row }">
                {{ formatPublishTime(row.publish_time) }}
            </template>
        </el-table-column>

        <!-- 文章状态 -->
        <el-table-column prop="status" label="状态" header-align="center">
            <template #default="scope">
                <el-tag :type="scope.row.deleted === 0 ? 'success' : 'info'">
                    {{ scope.row.deleted === 0 ? '已发布' : '草稿' }}
                </el-tag>
            </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column fixed="right" label="操作" width="120" header-align="center">
            <template #default="scope">
                <el-button link type="primary" size="small" @click.prevent="editArticle(scope.row)">
                    编辑
                </el-button>
                <el-button link type="danger" size="small" @click.prevent="deleteArticle(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination @page-change="pageChange" :total="totalItems" />
    <!-- 编辑文章 -->
    <edit :isOpen="drawer" :article="objArticle" @handle-close="handleClose" />
</template>

<script setup lang="ts">
    import pagination from './pagination.vue';
    import edit from './edit.vue';
    import { onMounted, ref } from 'vue';
    import { getArticleList, postDeleteArticle } from '@/api/index';
    interface ArticleParams {
        page: number;
        size: number;
        category: string;
        // 其他可能的参数
    }
    interface ArticleResponse {
        code: number;
        data: {
            list: any[]; // 根据实际情况定义类型
            total: number;
        };
    }
    const params = {
        category: 'all', // 文章分类（可选）
        page: 1,       // 当前页码
        size: 8,      // 每页条数
    };
    const totalItems = ref < number > (0);
    const drawer = ref < boolean > (false);
    const objArticle = ref < any > ({});
    import dayjs from 'dayjs';
    import utc from 'dayjs/plugin/utc'; // 如果需要处理 UTC 时间
    dayjs.extend(utc);
    // 文章列表数据
    const articleList = ref < any > ([]);
    const stringToArray = (str, options = {}) => {
        // 合并默认选项
        const { trim = true, filterEmpty = true } = options;
        // 处理空值情况
        if (typeof str !== 'string' || !str.trim()) {
            return [];
        }
        // 分割字符串（支持中英文逗号）
        const result = str.split(/[，,]/);
        // 处理元素
        return result
            .map(item => trim ? item.trim() : item) // 可选：去除两端空格
            .filter(item => !filterEmpty || item !== ''); // 可选：过滤空元素
    }
    // 编辑文章
    const editArticle = (article: any) => {
        drawer.value = true;
        objArticle.value = article;
        article.category = stringToArray(article.category); // 更新为分类名称
        console.log('编辑文章:',);
        // 这里可以跳转到编辑页面，或者打开编辑弹窗
    };
    // 关闭编辑弹窗
    const handleClose = (value: boolean) => {
        console.log('关闭编辑弹窗:', value);
        drawer.value = value;
    };
    // 删除文章
    const deleteArticle = async (article: any) => {
        console.log('删除文章:', article);
        let res = await postDeleteArticle(article.id);
        console.log(res)
        if (res.code == 0) {
            ElMessage.success(res.msg);
            // 这里可以调用 API 删除文章，并更新 articleList
            articleList.value = articleList.value.filter((item) => item.id !== article.id);
        } else {
            ElMessage.error(res.msg);
        }
    };
    // 格式化发布时间
    const formatPublishTime = (time: string) => {
        return dayjs.utc(time).local().format('YYYY-MM-DD HH:mm:ss');
    };
    // 获取文章列表数据
    const fetchArticleList = async (params: ArticleParams): Promise<void> => {
        try {
            const res: ArticleResponse = await getArticleList(params);
            if (res.code === 0) {
                articleList.value = res.data.list;
                articleList.value.forEach((element, index) => {
                    articleList.value[index].tags = element.tags.split(',')
                });
                if (res.data.total !== undefined) {
                    // 检查total是否存在
                    totalItems.value = res.data.total;
                }
            } else {
                console.error('Failed to fetch article list:', res);
                // 可以在这里添加更多的错误处理逻辑，比如显示错误消息给用户
            }
        } catch (error) {
            console.error('Error fetching article list:', error);
            // 处理网络错误或其他异常
        }
    };
    const initialParams: ArticleParams = params;
    onMounted(() => {
        fetchArticleList(initialParams);
    })
    // 分页
    const pageChange = async (page: number) => {
        const newParams: ArticleParams = { ...params, page };
        console.log(newParams, 'newParams')
        await fetchArticleList(newParams);
    }
</script>

<style scoped>
    .el-tag {
        margin-right: 5px;
    }

    /* 确保表格宽度铺满 */
    .el-table {
        width: 100%;
    }

    /* 设置表格列自适应 */
    .el-table-column--flex {
        flex: 1;
    }

    /* 全局设置表头居中 */
    .el-table th>.cell {
        text-align: center;
    }

    .el-table .cell {
        text-align: center;
    }
</style>